package xdpm.nhom16.DAO;

import java.util.ArrayList;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public abstract class AbstractTuKhoaDAO<DTO> extends AbstractDAO<DTO> implements
		ISearchAble<DTO> {
	public AbstractTuKhoaDAO(SQLiteDatabase db) {
		super(db);
	}

	public ArrayList<DTO> search(String input) {

		String nameColumnTuKhoa = getNameColumnTuKhoa();
		String selection = getSelectionFindTuKhoa(input, nameColumnTuKhoa);
		Cursor cursor = this.database.query(getTableName(), getNameColumns(),
				selection, null, null, null, null);

		ArrayList<DTO> result = cursorToDTOs(cursor);
		return result;
	}

	protected String getSelectionFindTuKhoa(String input,
			String nameColumnTuKhoa) {
		return String.format("LENGTH(REPLACE('%s',%s,'')) !=  LENGTH('%s')",
				input, nameColumnTuKhoa, input);
	}

	public ArrayList<DTO> search(String input, Object parentId) {
		String nameColumnTuKhoa = getNameColumnTuKhoa();
		String selection = String.format("%s='%s'", getNameColumnRefIdParent(),
				String.valueOf(parentId))
				+ " AND "
				+ getSelectionFindTuKhoa(input, nameColumnTuKhoa);
		Cursor cursor = this.database.query(getTableName(), getNameColumns(),
				selection, null, null, null, null);
		ArrayList<DTO> result = cursorToDTOs(cursor);
		return result;
	}

	protected abstract String getNameColumnTuKhoa();

	protected abstract String getNameColumnRefIdParent();
}
